package net.dgg.zz.credential.company.service;

import net.dgg.iboss.base.util.CustomerNumberEncryptionUtil;
import net.dgg.iboss.base.util.DesUtil;
import net.dgg.iboss.base.util.StringUtils;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.zz.common.constant.CredentialConstant;
import net.dgg.zz.common.constant.SystemCommonConstant;
import net.dgg.zz.common.files.entity.Annex;
import net.dgg.zz.common.files.service.AnnexService;
import net.dgg.zz.common.utils.DateUtils;
import net.dgg.zz.credential.company.dao.CompanyDao;
import net.dgg.zz.credential.company.entity.Company;
import net.dgg.zz.credential.company.vo.CompanyVo;
import net.dgg.zz.credential.talent.service.TalentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CompanyService {
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private AnnexService annexService;
    @Autowired
    private TranslateUtil translateUtil;
    @Autowired
    private DesUtil desUtil;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationManager organizationManager;
    @Autowired
    private TalentService talentService;

    public List<Company> selectComByWithPage(Map params){
        try {
            UserEntity user = sessionManager.getCurrentUser();
            params.put("orderDir", "desc");
            params.put("orderColumn", "create_time");
            if(params.containsKey("contactPhone1") && !StringUtils.isEmpty(params.get("contactPhone1").toString())){
                params.put("contactPhone1",desUtil.encrypt(params.get("contactPhone1").toString()));
            }
            //猎头总监查看全部
            List<Long> listUserId = userService.findUserByRoleCode("HUNTING_ZJ");
            List<Long> listUser = userService.findUserByRoleCode("HUNTING_MANAGER");
            if(listUserId.contains(user.getId())){

            }else{
                if(listUser.contains(user.getId())){
                    params.put("createrId",user.getId());
                    List<Long> orgIds = organizationManager.findOrgIdByAncestorId(user.getOrgId());
                    params.put("orgIds", orgIds);
                }else{
                    params.put("trackerId",user.getId());
                }
            }
            List<Company> list = companyDao.selectComByWithPage(params);
            List<Company> newList = new ArrayList<>(list.size());
            if(list.size()>0){
                for(Company company : list){
                    company.setFiles(this.findFile(company.getId(),"company"));
                    company.setEntryTalent(talentService.getEntyTalent(company.getId()));
                    newList.add(company);
                }
            }
            String[] transColum = {"scale", "cooperateStatus"};
            list = translateUtil.translateList(transColum, newList);//翻译
            String[] hideColum = {"contactPhone"};//解密
            list = desUtil.decryptList(hideColum, list);
            list = CustomerNumberEncryptionUtil.encryptionList(hideColum, list);
            return list;
        }catch (Exception e){
            return null;
        }
    }

    public Integer count(Map params){
        return companyDao.count(params);
    }

    /**
     * 新增
     * @param params
     * @return
     */
    public Integer insertCompany(Map params){
        UserEntity userEntity = sessionManager.getCurrentUser();
        Company company = new Company();
        company.setId(Long.valueOf(params.get("id").toString()));
        company.setCompanyName(params.get("companyName").toString());
        company.setContactPhone(desUtil.encrypt(params.get("contactPhone").toString()));
        if(!StringUtils.isEmpty(params.get("contractEndDate").toString())){
            company.setContractEndDate(DateUtils.getDate(params.get("contractEndDate").toString(),"yyyy-MM-dd"));
        }
        if(!StringUtils.isEmpty(params.get("contractStartDate").toString())){
            company.setContractStartDate(DateUtils.getDate(params.get("contractStartDate").toString(),"yyyy-MM-dd"));
        }
        company.setContractNo(params.get("contractNo").toString());
        if(!StringUtils.isEmpty(params.get("salaryMax").toString())){
            company.setSalaryMax(Integer.valueOf(params.get("salaryMax").toString()));
        }
        if(!StringUtils.isEmpty(params.get("salaryMin").toString())){
            company.setSalaryMin(Integer.valueOf(params.get("salaryMin").toString()));
        }
        company.setContactName(params.get("contactName").toString());
        company.setCooperateStatus(CredentialConstant.COOP_STATUS_NOT);
        company.setIndustry(params.get("industry").toString());
        company.setJobDuty(params.get("jobDuty").toString());
        if(!StringUtils.isEmpty(params.get("num").toString())){
            company.setNum(Integer.valueOf(params.get("num").toString()));
        }
        company.setPosition(params.get("position").toString());
        company.setScale(params.get("scale").toString());
        company.setCreateUser(userEntity);
        return companyDao.insert(company);
    }

    /**
     * 修改
     * @param params
     * @return
     */
    public Integer updateCompany(Map params){
        UserEntity userEntity = sessionManager.getCurrentUser();
        Company company = companyDao.selectByPrimaryKey(Long.valueOf(params.get("id").toString()));
        company.setCompanyName(params.get("companyName").toString());
        if(!StringUtils.isEmpty(params.get("contractEndDate").toString())){
            company.setContractEndDate(DateUtils.getDate(params.get("contractEndDate").toString(),"yyyy-MM-dd"));
        }
        if(!StringUtils.isEmpty(params.get("contractStartDate").toString())){
            company.setContractStartDate(DateUtils.getDate(params.get("contractStartDate").toString(),"yyyy-MM-dd"));
        }
        company.setContractNo(params.get("contractNo").toString());
        if(!StringUtils.isEmpty(params.get("salaryMax").toString())){
            company.setSalaryMax(Integer.valueOf(params.get("salaryMax").toString()));
        }
        if(!StringUtils.isEmpty(params.get("salaryMin").toString())){
            company.setSalaryMin(Integer.valueOf(params.get("salaryMin").toString()));
        }
        String oldPhone = StringUtils.encryptionNumber(desUtil.decrypt(company.getContactPhone()));
        String newPhone = params.get("contactPhone").toString();
        if(!oldPhone.equals(newPhone)){
            company.setContactPhone(desUtil.encrypt(params.get("contactPhone").toString()));
        }
        company.setContactName(params.get("contactName").toString());
        company.setIndustry(params.get("industry").toString());
        company.setJobDuty(params.get("jobDuty").toString());
        if(!StringUtils.isEmpty(params.get("num").toString())){
            company.setNum(Integer.valueOf(params.get("num").toString()));
        }
        company.setPosition(params.get("position").toString());
        company.setScale(params.get("scale").toString());
        company.setUpdaterUser(userEntity);
        return companyDao.updateByPrimaryKey(company);
    }

    /**
     * 查找附件
     * @param id
     * @param type
     * @return
     */
    public String findFile(Long id,String type){
        String fileId = SystemCommonConstant.ANNEX_FILE_ID_PREFIX + "_" + id+ "_" + type;
        List<Annex> files = annexService.findFile(fileId);
        String returnStr="";
        if (null != files) {
            for (Annex file : files) {
                returnStr +=file.getFilename()+"<br/>";
            }
        }
        return returnStr;
    }
    /**
     * 查询跟踪人
     */
    public List<Map> findTracker(){
        return companyDao.selectTracker();
    }

    /**
     * 通过id查公司信息
     * @param id
     * @return
     */
    public Company getCompanyById(Long id) {
        Company company = companyDao.selectByPrimaryKey(id);
        company.setContactPhone(StringUtils.encryptionNumber(desUtil.decrypt(company.getContactPhone())));
        return company;
    }

    /**
     * 通过id查联系人电话
     * @param id
     * @return
     */
    public String getContactPhoneById(Long id) {
        String returnStr = null;
        Company company = companyDao.selectByPrimaryKey(id);
        if(null != company){
            returnStr = desUtil.decrypt(company.getContactPhone());
        }
        return returnStr;
    }

    public Integer updateCompanyTracker(Map params) {
        UserEntity userEntity = sessionManager.getCurrentUser();
        Company company = companyDao.selectByPrimaryKey(Long.valueOf(params.get("id").toString()));
        if( params.containsKey("trackerId") && !StringUtils.isEmpty(params.get("trackerId").toString()) ){
            Long trackerId = Long.parseLong(params.get("trackerId").toString());//跟踪人员id
            UserEntity tracker = userService.findUserById(trackerId);//跟踪人
            company.setTrackerId(trackerId);
            company.setTrackerUserName(tracker.getRealName().concat(tracker.getLoginName()));
            company.setTrackerUserOrgId(tracker.getOrgId());
        }
       if(params.containsKey("cooperateStatus") && !StringUtils.isEmpty(params.get("cooperateStatus").toString())){
           company.setCooperateStatus(params.get("cooperateStatus").toString());
       }
        company.setUpdaterUser(userEntity);
        return companyDao.updateByPrimaryKey(company);
    }
    public List<Map> getCompanyList(){
        List<Map> list = companyDao.selectCompany();
        return list;
    }

    public List<CompanyVo> findExportCompany(Map params) {
        List<CompanyVo> newList = new LinkedList<>();
        List<Company> list = this.selectComByWithPage(params);
        for(Company company : list){
            CompanyVo companyVo = new CompanyVo();
            companyVo.setCompanyName(null == company.getCompanyName() ? "" : company.getCompanyName());
            companyVo.setContactName(null == company.getContactName() ? "" : company.getContactName());
            companyVo.setContactPhone(null == company.getContactPhone() ? "" : company.getContactPhone());
            String contactDate = "";
            if(null !=company.getContractStartDate() && null != company.getContractEndDate()){
                contactDate = DateUtils.dateString(company.getContractStartDate(),"yyyyMMdd")+"—"+DateUtils.dateString(company.getContractEndDate(),"yyyyMMdd");
            }
            companyVo.setContractDate(contactDate);
            companyVo.setContractNo(null == company.getContractNo() ? "" : company.getContractNo());
            companyVo.setCooperateStatus(null == company.getCooperateStatus() ? "" : company.getCooperateStatus());
            companyVo.setEntryTalent(null == company.getEntryTalent() ?  "" : company.getEntryTalent());
            companyVo.setIndustry(null == company.getIndustry() ? "" : company.getIndustry());
            companyVo.setJobDuty(null == company.getJobDuty() ? "" : company.getJobDuty());
            companyVo.setNum(null == company.getNum() ? "" : company.getNum().toString());
            companyVo.setPosition(null == company.getPosition() ? "" : company.getPosition());
            companyVo.setScale(null == company.getScale() ? "" : company.getScale());
            companyVo.setTrackerUserName(null == company.getTrackerUserName() ? "" : company.getTrackerUserName());
            String salary ="";
            if(null != company.getSalaryMin() && null != company.getSalaryMax()){
                salary = company.getSalaryMin().toString()+"—"+company.getSalaryMax().toString()+"K";
            }
            companyVo.setSalary(salary);
            newList.add(companyVo);
        }
        return newList;
    }
    /**
     * 新增判重
     */
    public boolean isExist(Map params){
        if(null == params.get("contractNo").toString() || "" .equals( params.get("contractNo").toString())){
            return false;
        }
        Integer count = companyDao.queryExist(params);
        if(count>0){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 编辑判重
     */
    public boolean isExistEdit(Map params){
        if(null == params.get("contractNo").toString() || "" .equals( params.get("contractNo").toString())){
           return false;
        }
        Integer count = companyDao.queryExistEdit(params);
        if(count>0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取企业库电话未解密
     * @param id
     * @return
     */
    public Company getCompanyByIdNotDe(Long id) {
        Company company = companyDao.selectByPrimaryKey(id);
        return company;
    }
}
